﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using Obligatorio2013.Clases;
using Obligatorio2013.Persistencia;
using Obligatorio2013.Logging;

namespace Obligatorio2013.Modelo
{
    public class UserController
    {


        #region Singleton
        private readonly static UserController _instance = new UserController();
        public static UserController Instance { get { return _instance; } }
        private UserController()
        {
            try
            {
                // TODO: Nico aca inicializar todas las listas
                this.userList = userDao.getAll().Cast<Users>().ToList();
                Log.Instance.Info("Usuarios cargados : " + this.userList.Count);
            }
            catch (Exception ex) { Log.Instance.Error("Error cargando lista : " + ex.StackTrace); }

        }
        #endregion


        private List<Users> userList = new List<Users>();
        private UsuarioDAO userDao = new UsuarioDAO();

        public List<Users> UserList
        {
            get { return this.userList; }
        }
        #region methods

        private bool validateUser(string mail)
        {

            if (!string.IsNullOrEmpty(mail) && this.UserList != null)
            {
                foreach (Users usr in this.UserList)
                {
                    if (usr.UserEmail.Equals(mail))
                        return true;
                }
            }

            return false;

        }

        private bool userExists(Users usr)
        {
            if (this.UserList != null)
            {
                foreach (Users u in this.UserList)
                {
                    if (u.Equals(usr))
                        return true;
                }
            }
            return false;
        }

        private void addUserList(Users u)
        {
            if (this.UserList == null) userList = new List<Users>();
            this.UserList.Add(u);
        }


        private void removeUserList(Users u)
        {
            if (this.UserList != null) { this.UserList.Remove(u); };
        }

        private void suspendUser(Users usr)
        {
            if (this.UserList != null)
            {
                foreach (Users u in this.UserList)
                {
                    if (u.Equals(usr))
                        u.UserActive = false;
                }
            }

        }

        public bool saveUser(Users u)
        {
            if (!userExists(u))
            {
                if (userDao.Save(u))
                {
                    addUserList(u);
                    return true;   
                }
            }
            return false;
        }

        public bool updateUsers(Users u)
        {
            if (userExists(u))
            {
                if (userDao.Update(u))
                {
                    removeUserList(u);
                    addUserList(u);
                    return true;   
                }
            }
            return false;
        }
        public List<Users> getUsersByStatus(bool all, bool active)
        {
            List<Users> ret = null;
            if (UserList != null)
            {
                if (all)
                {
                    return UserList;
                }
                else if (active)
                {
                    foreach (Users u in this.UserList)
                    {
                        if (u.UserActive)
                        {
                            if (ret == null) ret = new List<Users>();
                            ret.Add(u);
                        }

                    }
                }
                else
                {
                    foreach (Users u in this.UserList)
                    {
                        if (!u.UserActive)
                        {
                            if (ret == null) ret = new List<Users>();
                            ret.Add(u);
                        }
                    }
                }

            }
            return ret;
        }


        public Users getUserById(string mail)
        {

            if (UserList != null)
            {
                foreach (Users users in this.UserList)
                {
                    if (users.UserEmail == mail)
                    {
                        return users;
                    }
                }
            }
            return null;

        }


        /*   Dado un usuario y una password primero verifica que no sean nullos o vacios, itera sobre la lista de usauarios 
 * y verifica. */
        public Users login(string user, string pass)
        {

            if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(pass) && this.UserList != null)
            {
                foreach (Users usr in this.UserList)
                {
                    if (usr.User.Equals(user) && usr.UserPass.Equals(pass))
                        return usr;
                }
            }
            return null;
        }

        #endregion


        #region validations

        public bool validateUserPass(string user, string pass)
        {
            if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(pass))
            {
                // Valido largos
                if (4 < user.Length && user.Length < 12 && 4 < pass.Length && pass.Length < 13)
                {
                    //(Entre 8 y 10 caracteres, por lo menos un digito y un alfanumérico, y no puede contener caracteres espaciales)
                    Regex regexUser = new Regex(@"(?!^[a-zA-Z]*$)^([a-zA-Z]{5,12})$");
                    Regex regexPass = new Regex(@"(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{5,12})$");
                    // return (regexUser.IsMatch(user) && regexPass.IsMatch(pass));
                    return (regexPass.IsMatch(pass));
                }
            }

            // www.entrecodigos.net/2012/08/c-validacion-con-expresiones-regulares/
            return false;
        }

        public bool validateEmail(string mail)
        {
            Regex regex = new Regex(@"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$");

            return regex.IsMatch(mail);
        }

        // formato 222-3333
        public bool validatePhone(string phone)
        {
            Regex regex = new Regex(@"^([0-9]{3})[-. ]?([0-9]{4})$");
            return regex.IsMatch(phone);
        }
        #endregion

    }
}